// Vuex 日志插件
// 这个插件演示了如何记录和分析Vuex状态变化

export default function createLoggerPlugin(options = {}) {
    const {
        collapsed = true,          // 是否折叠日志组
        filter = () => true,       // 过滤要记录的mutations
        transformer = state => state, // 转换状态用于日志显示
        mutationTransformer = mut => mut, // 转换mutation用于日志显示
        actionFilter = () => true, // 过滤要记录的actions
        actionTransformer = (action, state) => action, // 转换action用于日志显示
        logMutations = true,       // 是否记录mutations
        logActions = true,         // 是否记录actions
        logger = console           // 日志输出对象
    } = options
    
    return store => {
        let prevState = deepCopy(store.state)
        
        // 订阅mutations
        if (logMutations) {
            store.subscribe((mutation, state) => {
                if (filter(mutation, prevState, state)) {
                    const startTime = performance.now()
                    
                    if (collapsed) {
                        logger.groupCollapsed(
                            `%cmutation %c${mutation.type}%c @ ${new Date().toLocaleTimeString()}`,
                            'color: #9E9E9E; font-weight: bold',
                            'color: #03A9F4; font-weight: bold', 
                            'color: #9E9E9E'
                        )
                    } else {
                        logger.group(
                            `mutation ${mutation.type} @ ${new Date().toLocaleTimeString()}`
                        )
                    }
                    
                    logger.log('%cprev state', 'color: #9E9E9E; font-weight: bold', transformer(prevState))
                    logger.log('%cmutation', 'color: #03A9F4; font-weight: bold', mutationTransformer(mutation))
                    logger.log('%cnext state', 'color: #4CAF50; font-weight: bold', transformer(state))
                    
                    const endTime = performance.now()
                    logger.log(`%cmutation duration: ${(endTime - startTime).toFixed(2)}ms`, 'color: #FF9800')
                    
                    logger.groupEnd()
                    
                    prevState = deepCopy(state)
                }
            })
        }
        
        // 订阅actions
        if (logActions) {
            store.subscribeAction({
                before: (action, state) => {
                    if (actionFilter(action, state)) {
                        logger.groupCollapsed(
                            `%caction %c${action.type}%c @ ${new Date().toLocaleTimeString()}`,
                            'color: #9E9E9E; font-weight: bold',
                            'color: #FF9800; font-weight: bold',
                            'color: #9E9E9E'
                        )
                        logger.log('%caction', 'color: #FF9800; font-weight: bold', actionTransformer(action, state))
                        logger.log('%cstate before', 'color: #9E9E9E; font-weight: bold', transformer(state))
                    }
                },
                after: (action, state) => {
                    if (actionFilter(action, state)) {
                        logger.log('%cstate after', 'color: #4CAF50; font-weight: bold', transformer(state))
                        logger.groupEnd()
                    }
                },
                error: (action, state, error) => {
                    if (actionFilter(action, state)) {
                        logger.error('%caction error', 'color: #F44336; font-weight: bold', error)
                        logger.groupEnd()
                    }
                }
            })
        }
    }
}

// 工具函数：深拷贝
function deepCopy(obj) {
    if (obj === null || typeof obj !== 'object') {
        return obj
    }
    
    if (obj instanceof Date) {
        return new Date(obj.getTime())
    }
    
    if (obj instanceof Array) {
        return obj.map(item => deepCopy(item))
    }
    
    if (typeof obj === 'object') {
        const copy = {}
        Object.keys(obj).forEach(key => {
            copy[key] = deepCopy(obj[key])
        })
        return copy
    }
}

// 使用示例：
// import createLoggerPlugin from '@/store/plugins/logger'
// 
// const loggerPlugin = createLoggerPlugin({
//     collapsed: false,
//     filter: (mutation, prevState, nextState) => {
//         // 只记录特定的mutations
//         return mutation.type.indexOf('SET_') !== -1
//     },
//     transformer: state => {
//         // 只显示状态的特定部分
//         return {
//             user: state.user,
//             loading: state.loading
//         }
//     }
// })
// 
// export default new Vuex.Store({
//     // ... 其他配置
//     plugins: process.env.NODE_ENV !== 'production' ? [loggerPlugin] : []
// })